package com.hmsm.sys.action;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.hmsm.dingtalk.Department;
import com.hmsm.dingtalk.DingTalkClient;
import com.hmsm.dingtalk.User;
import com.hmsm.rtx.RTXClient;
import com.hmsm.rtx.RTXDept;
import com.hmsm.rtx.RTXUser;
import com.hmsm.sys.bean.DeptTypeEnum;
import com.hmsm.sys.bean.LocalDept;
import com.hmsm.sys.bean.LocalRole;
import com.hmsm.sys.bean.LocalUser;
import com.hmsm.sys.bean.RTXDeptBean;
import com.hmsm.sys.bean.RTXUserBean;
import com.hmsm.sys.service.IOrgService;
import com.hmsm.sys.service.IRoleInfoService;
import com.hmsm.sys.service.IUserService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
public class OrgTreeHelper{

	private static final Log log = LogFactory.getLog(OrgTreeHelper.class);
	
	public static final String ROOT_KEY = "rootDept";

	private RTXDeptBean rootDept = null;

	public RTXDeptBean getRootDept() {
		return rootDept;
	}

	public void setRootDept(RTXDeptBean rootDept, LocalUser currentUser) {
		this.rootDept = rootDept;
	}

	private boolean simpleFormat = true;
	
	public boolean isSimpleFormat() {
		return simpleFormat;
	}

	public void setSimpleFormat(boolean simpleFormat) {
		this.simpleFormat = simpleFormat;
	}
	
	@Resource
	private IRoleInfoService roleInfoService;

	@Resource
	private IOrgService orgService;

	public IOrgService getOrgService() {
		return orgService;
	}

	public void setOrgService(IOrgService orgService) {
		this.orgService = orgService;
	}

	@Resource
	private IUserService userService;;
	
	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	private List<LocalDept> removeDepts = new ArrayList<LocalDept>();


	/**
	 * 递归添加组织机构节点
	 * @param nodes 结果集合
	 * @param rtxDeptBean 要添加的节点
	 * @param syncNeed 为空时不考虑同步远程组织机构，非空时表示当前节点是否需要同步
	 * @param depth 加载深度
	 * @param simpleData 是否使用简单节点数据格式
	 */
	public void addDeptNode(JSONArray nodes, RTXDeptBean rtxDeptBean, Class<?> bizClass, Collection<Integer> ids, Boolean syncNeed, boolean onlyAdd, int depth, boolean simpleData){
		JSONObject jsonObject = new JSONObject();
		
		jsonObject.put("id", "o-"+rtxDeptBean.getId());
		LocalDept deptInfo = rtxDeptBean.getBindDept();
		
		if (simpleData) {
			if (rtxDeptBean.getParent()!=null){
				jsonObjSetParent(jsonObject, rtxDeptBean.getParent());
			}
		}
		
		// 部门节点，肯定是parent节点
		jsonObject.put("isParent", true);

		boolean nocheck = true;

		String name = "";
		if (deptInfo!=null){
			jsonObject.put("deptId", deptInfo.getPkId());
		}
		if(syncNeed!=null){
			boolean remoteOrgFaile = false;
			if (!syncNeed){
				// 本级之上还不需要进行同步处理
				syncNeed = rtxDeptBean.getLevel()>0&&deptInfo!=null&&deptInfo.getRelevanceConfig()!=null&&deptInfo.getRelevanceConfig().startsWith("{")&&deptInfo.getRelevanceConfig().endsWith("}");
				if (syncNeed){
					remoteOrgFaile = false;
				}
			}
			
			if(syncNeed&&!remoteOrgFaile){
				nocheck = false;

				if(rtxDeptBean.getRelevanceId()==null){
					LocalDept parent = rtxDeptBean.getParent().getBindDept();
					if (deptInfo.getAllDepts().size() > 0 || deptInfo.getAllUsers().size() > 0) {
						name += deptInfo.getPath(parent) + deptInfo.getName() + "[删除]" + "("
								+ (deptInfo.getAllDepts().size() > 0 ? deptInfo.getAllDepts().size() + "部门" : "")
								+ (deptInfo.getAllUsers().size() > 0 ? deptInfo.getAllUsers().size() + "人" : "") + ")";
					} else {
						name += deptInfo.getPath(parent) + deptInfo.getName() + "[删除]";
					}
					jsonObject.put("delDeptId", rtxDeptBean.getId());
				}else{	
					name += rtxDeptBean.isOrganization()?("["+rtxDeptBean.getDeptName()+"]"):rtxDeptBean.getDeptName();
					if (deptInfo != null) {
						boolean update = false;
						boolean checked = deptInfo.getIdType()!=null&&deptInfo.getIdType()>0&&rtxDeptBean.getRelevanceId()!=null&&deptInfo.getIdType().intValue()==rtxDeptBean.getRelevanceId(); 
						if (rtxDeptBean.getRelevanceId()!=null&&deptInfo.getIdType()!=null&&rtxDeptBean.getRelevanceId().longValue()!=deptInfo.getIdType().longValue()){
							update = true;
						}
						if (!deptInfo.getName().equals(rtxDeptBean.getDeptName())) {
							name += "[原名]" + deptInfo.getName();
							update = true;
							checked = false;
						}
						if (deptInfo.getParent() != null && rtxDeptBean.getParent()!=null && deptInfo.getParent().getPkId()>0 && !deptInfo.getParent().equals(rtxDeptBean.getParent().getBindDept())) {
							name += "[转自]" + deptInfo.getParent().getName();
							checked = false;
							update = true;
						}
						jsonObject.put("checked", checked);
						if (update){
							jsonObject.put("updDeptId", rtxDeptBean.getId());
						}
					} else {
						jsonObject.put("addDeptId", rtxDeptBean.getId());
						name += "[添加]";
					}
				}
			}else{
				name += rtxDeptBean.isOrganization()?("["+rtxDeptBean.getDeptName()+"]"):rtxDeptBean.getDeptName();
			}
		}else{
			name += rtxDeptBean.isOrganization()?(""+rtxDeptBean.getDeptName()+""):rtxDeptBean.getDeptName();
			if(ids!=null){
				if(LocalDept.class.isAssignableFrom(bizClass)){
					nocheck = ids.contains(deptInfo.getPkId());
				}else if(LocalUser.class.isAssignableFrom(bizClass)){
					nocheck = ids.contains(deptInfo.getPkId());
				}
			}
		}
		
		// 上两级默认展开
		jsonObject.put("open", depth==-1||depth>0); // rtxDeptBean.getLevel()<1||syncNeed!=null&&syncNeed
		
		jsonObject.put("name", name);
		if (nocheck){
			jsonObject.put("nocheck", nocheck);
		}

		JSONArray subNodes;
		if (!simpleData) {
			subNodes = new JSONArray();
		} else {
			subNodes = nodes;
		}

		// 递归处理下级部门
		if (depth ==-1 ||depth > 1) {
			if (depth > 1) {
				depth--;
			}
	
			addUsersAndSubNodes(subNodes, rtxDeptBean, bizClass, ids, syncNeed, onlyAdd, depth, simpleData);
			
		}

		if (!simpleData) {
			jsonObject.put("children", subNodes);
		}
		nodes.add(jsonObject);
	}

	private void jsonObjSetParent(JSONObject jsonObject, RTXDeptBean rtxDeptBean) {
		jsonObject.put("pId", "o-" + rtxDeptBean.getId());
	}

	/**
	 * 添加部门子节点，包括直属用户和下级部门
	 * @param nodes			返回处理结果
	 * @param rtxDeptBean	当前处节点
	 * @param bizClass		关联业务类类型
	 * @param ids			选择框关联ids
	 * @param syncNeed
	 * @param depth 		只是应该等于1,大于1时进行有限递归，等于-1则无限递归
	 * @param simpleData 	是否使用简单树节点格式
	 */
	public void addUsersAndSubNodes(JSONArray nodes, RTXDeptBean rtxDeptBean, Class<?> bizClass, Collection<Integer> ids, Boolean syncNeed, boolean onlyAdd, int depth, boolean simpleData) {
		if (depth == -1 || depth>0) {
			
			if (syncNeed!=null&&syncNeed){
				if(rtxDeptBean.getRelevanceId()!=null){
					// 正常部门
					addOldAndMoveInUserList(nodes, rtxDeptBean, syncNeed, simpleData);

					// 添加新加用户列表
					addNewUserList(nodes, rtxDeptBean, simpleData);
					if (rtxDeptBean.getBindDept()!=null){
						// 添加转出用户列表
						addMoveOutUserList(nodes, rtxDeptBean, simpleData);
						// 添加删除用户列表
						addRemoveUserList(nodes, rtxDeptBean, simpleData);
					}
					
					// 添加原有、转入及添加的部门
					for (Object deptBean : rtxDeptBean.getSubDepts()) {
						RTXDeptBean subDeptBean = (RTXDeptBean) deptBean;
						addDeptNode(nodes, subDeptBean, bizClass, ids, syncNeed, onlyAdd, depth, simpleData);
					}
					
					if (rtxDeptBean.getBindDept()!=null){
						// 添加转出的部门
						addMoveOutSubDepts(nodes, rtxDeptBean, simpleData);
						// 添加要删除的部门
						addRemoveSubDepts(nodes, rtxDeptBean, depth, simpleData);
					}
					
				}else{
					// 要删除的部门
					// 添加转出用户列表
					addMoveOutUserList(nodes, rtxDeptBean, simpleData);
					// 添加删除用户列表
					addRemoveUserList(nodes, rtxDeptBean, simpleData);
					
					// 已经要删除的部门下的部门，添加原有的部门标记为删除
					for (Object dept : rtxDeptBean.getBindDept().getSubDepts()) {
						LocalDept subDept = (LocalDept) dept;
						RTXDeptBean subDeptBean = (RTXDeptBean) subDept.getBindDepart();
						if (subDeptBean==null){
							subDeptBean = new RTXDeptBean(subDept);
							subDeptBean.setSubDepts(new ArrayList<RTXDeptBean>());
							subDeptBean.setParent(rtxDeptBean);
							subDept.setBindDepart(subDeptBean);
							putDeptMap(subDeptBean, null, rootDept);
						}
						try {
							orgService.loadRefObjectListMap(subDept);
						} catch (Exception e) {
							e.printStackTrace();
						}
						removeDepts.add(subDept);

						addDeptNode(nodes, subDeptBean, bizClass, ids, syncNeed, onlyAdd, depth, simpleData);
					}
				}
			}else{
				if(ids!=null&&(bizClass==null||LocalUser.class.isAssignableFrom(bizClass))){
					// 有业务数据（用户数据）需要处理
					// 添加用户列表
					addUserList(nodes, rtxDeptBean, ids, onlyAdd, simpleData);
				}
				
				// 添加原有、转入及添加的部门
				for (Object deptBean : rtxDeptBean.getSubDepts()) {
					RTXDeptBean subDeptBean = (RTXDeptBean) deptBean;
					addDeptNode(nodes, subDeptBean, bizClass, ids, syncNeed, onlyAdd, depth, simpleData);
				}
			}
			
		}
	}

	/**
	 * 添加原有及转入用户
	 * @param rtxDeptBean
	 * @param simpleData
	 * @param syncNeed
	 * @param simpleData
	 */
	private void addUserList(JSONArray nodes, RTXDeptBean rtxDeptBean, Collection<Integer> userIds, boolean onlyAdd, boolean simpleData) {
		LocalDept deptInfo = rtxDeptBean.getBindDept();
		for (Object user : deptInfo.getUsers()) {
			LocalUser userInfo = (LocalUser) user;
			RTXUserBean userBean = userInfo.getBindUser();
			if (userBean!=null){
				JSONObject jsonUser = null;
				
				jsonUser = new JSONObject();
				
				jsonUser.put("id", "u-" + userBean.getId());
				if (simpleData) {
					jsonObjSetParent(jsonUser, rtxDeptBean);
				}
				jsonUser.put("userId", userInfo.getPkId());
				jsonUser.put("name", userBean.getName() + (userBean.getName().equals(userBean.getUserName()) ? "" : "(" + userBean.getUserName() + ")"));
				jsonUser.put("isParent", false);
				if(onlyAdd){
					jsonUser.put("nocheck", userIds.contains(userInfo.getPkId()));
				}else{
					jsonUser.put("checked", userIds.contains(userInfo.getPkId()));
				}

				nodes.add(jsonUser);
			}
		}
	}

	/**
	 * 添加原有及转入用户
	 * @param deptNodeBean
	 * @param simpleData
	 * @param syncNeed
	 * @param simpleData
	 */
	private void addOldAndMoveInUserList(JSONArray nodes, RTXDeptBean deptNodeBean, Boolean syncNeed, boolean simpleData) {
		LocalDept localDept = deptNodeBean.getBindDept();
		RTXDeptBean syncRootDept = deptNodeBean.getSyncRootDept();
		
		if (deptNodeBean.getUsers()!=null){
			// 遍历当前部门节点下的用户
			for (Object user : deptNodeBean.getUsers()) {
				RTXUserBean userBean = (RTXUserBean) user;
				LocalUser userInfo = userBean.getBindUser();
				if (userBean.getRelevanceId() != null&&userInfo!=null){
					JSONObject jsonUser = null;
					
					jsonUser = new JSONObject();
					
					// 原有用户
					jsonUser.put("id", "u-" + userBean.getId());
					if (simpleData) {
						jsonObjSetParent(jsonUser, deptNodeBean);
					}
					jsonUser.put("isParent", false);

					String name;
					boolean nocheck = true;
					boolean checked = true;
					name = userBean.getName() + (userBean.getName().equals(userBean.getUserName()) ? "" : "(" + userBean.getUserName() + ")");
					if(syncNeed!=null){
						if (syncNeed){
							
							if (!userInfo.affiliatedWithDepart(localDept)) {
								LocalDept removedDept = null;
								if(userInfo.getUserDepts()==null){
									userInfo.setUserDepts(new ArrayList<LocalDept>());
								}
								for(Object dept:userInfo.getUserDepts()){
									LocalDept userDept = (LocalDept) dept;
									RTXDeptBean dd = (RTXDeptBean) userDept.getBindDepart();
									if(dd==null){
										removedDept = userDept;
									}else{
										log.debug("dd");
									}
								}
								if (removedDept!=null){
									name += "[转自]" + removedDept.getName();
								}else{
									name += "[加入]";
								}
								checked = false;
								nocheck = false;
							}
							if(userInfo.getIdType()==null||!userInfo.getIdType().equals(userBean.getRelevanceId())){
								name += "[更新]";
								checked = false;
								nocheck = false;
							}
							
							if (!nocheck){
								jsonUser.put("updUserId", userBean.getId());
							}
						}
						
						try {
							if (rootDept.getBindDept().getUserLoginNameMap()!=null&&((Set<Integer>) rootDept.getBindDept().getUserLoginNameMap().get(userInfo.getUserName())).size()>1){
								jsonUser.put("updUserId", userBean.getId());
								nocheck = false;
								checked = false;
								name +="[重名]";
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
					jsonUser.put("name", name);
					if (nocheck){
						jsonUser.put("nocheck", nocheck);
					}else{
						jsonUser.put("checked", checked);
					}
					
					nodes.add(jsonUser);
				}
			}
		}
	}

	/**
	 * 添加迁出用户，仅显示，不操作
	 * @param rtxDeptBean
	 * @param simpleData
	 * @param syncNeed
	 * @param simpleData
	 */
	private void addMoveOutUserList(JSONArray nodes, RTXDeptBean rtxDeptBean, boolean simpleData) {
		LocalDept deptInfo = rtxDeptBean.getBindDept();
		if (deptInfo!=null){
			for(Object user: deptInfo.getUsers()){
				LocalUser userInfo = (LocalUser) user;
				RTXUserBean userBean = userInfo.getBindUser();
				if (userBean!=null&&!userBean.affiliatedWithDepart(rtxDeptBean)){  // userBean!=null&&userInfo.getDepart()!=null&&userBean.getDepart()!=null&&!userInfo.getDepart().equals(userBean.getDepart().getBindDept())
					JSONObject  jsonUser = new JSONObject();
					jsonUser.put("id", "u-" + userBean.getId());
					if (simpleData) {
						jsonObjSetParent(jsonUser, rtxDeptBean);
					}
					jsonUser.put("isParent", false);
					jsonUser.put("updUserId", userBean.getRelevanceId());
					
					boolean nocheck = true;
					String name = userInfo.getName() + (userInfo.getName().equals(userInfo.getUserName()) ? "" : "(" + userInfo.getUserName() + ")");

					try {
						if (((Set<Integer>) rootDept.getBindDept().getUserLoginNameMap().get(userInfo.getUserName())).size()>1){
							jsonUser.put("updUserId", userBean.getId());
							nocheck = false;
							name +="[重名]";
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					String newDepts = "";
					for(RTXDeptBean rtxUserDept:userBean.getUserDepts()){
						for(Object dept:userInfo.getUserDepts()){
							LocalDept localDept = (LocalDept) dept;
							if (!localDept.equals(rtxUserDept.getBindDept())){
								RTXDeptBean newDept = rtxUserDept;
								if (newDepts.length()>0){
									newDepts += "|";
								}
								newDepts += newDept.getDeptName();
							}
						}
					}
					name += "[转到]"+newDepts;
					
					jsonUser.put("name", name);
					if(nocheck){
						jsonUser.put("nocheck", nocheck);
					}
	
					nodes.add(jsonUser);
				}
			}
		}
	}

	/**
	 * 添加新用户
	 * @param rtxDeptBean
	 * @param simpleData
	 * @param syncNeed
	 * @param nodes
	 */
	private void addNewUserList(JSONArray nodes, RTXDeptBean rtxDeptBean, boolean simpleData) {
		if(rtxDeptBean.getUsers()!=null){
			for (Object user : rtxDeptBean.getUsers()) {
				RTXUserBean userBean = (RTXUserBean) user;
				if(userBean.getBindUser()==null){
					JSONObject jsonUser = null;
					
					jsonUser = new JSONObject();
					
					if (simpleData) {
						jsonObjSetParent(jsonUser, rtxDeptBean);
					}
					jsonUser.put("id", "u-" + userBean.getId());
					jsonUser.put("isParent", false);
					jsonUser.put("addUserId", userBean.getId());
		
					jsonUser.put("name", userBean.getName() + (userBean.getName().equals(userBean.getUserName()) ? "" : "(" + userBean.getUserName() + ")")+"[添加]");
					jsonUser.put("checked", false);
		
					nodes.add(jsonUser);
				}
			}
		}
	}

	/**
	 * 添加要转出的部门
	 * @param jsonArray
	 * @param rtxParentBean
	 * @param simpleData
	 */
	private void addMoveOutSubDepts(JSONArray jsonArray, RTXDeptBean rtxParentBean, boolean simpleData){
		LocalDept parent = rtxParentBean.getBindDept();
		if (parent!=null){
			List<RTXDeptBean> list = rtxParentBean.getMoveOutDepts();
			if(list==null){
				list = new ArrayList<RTXDeptBean>();
				rtxParentBean.setMoveOutDepts(list);
				for (Object dept : parent.getSubDepts()){
					LocalDept deptInfo = (LocalDept) dept;
					RTXDeptBean rtxDept = (RTXDeptBean)deptInfo.getBindDepart();
					// 原部门下的 部门中 有绑定对象 但 
					if (rtxDept != null&&rtxDept.getRelevanceId()!=null&&!parent.equals(rtxDept.getParent().getBindDept())){
						rtxDept = new RTXDeptBean(deptInfo);
						putDeptMap(rtxDept, null, rootDept);
						list.add(rtxDept);
					}
				}
			}
			for (RTXDeptBean rtxDept : list){
				LocalDept deptInfo = rtxDept.getBindDept();
				JSONObject jsonObject = new JSONObject();
				
				// 转出节点
				jsonObject.put("id", "o-" + rtxDept.getId());
				jsonObject.put("isParent", true);
				jsonObject.put("open", (deptInfo.getLevel() < 3));
				String name = deptInfo.getName()+"[转到]"+((RTXDeptBean)deptInfo.getBindDepart()).getParent().getBindDept().getName()+" 下";
				jsonObject.put("name", name);
				jsonObject.put("nocheck", true);
				if (simpleData) {
					if (rtxParentBean != null) {
						jsonObjSetParent(jsonObject, rtxParentBean);
					}
				}
				jsonArray.add(jsonObject);
			}
		}
	}

	/**
	 * 添加需要删除下级部门
	 * @param nodes
	 * @param rtxParentBean
	 * @param simpleData
	 */
	private void addRemoveSubDepts(JSONArray nodes, RTXDeptBean rtxParentBean, int depth, boolean simpleData){
		LocalDept parent = rtxParentBean.getBindDept();
		
		if (parent!=null){
			List<LocalDept> deptList = new ArrayList<LocalDept>();
			deptList = parent.getSubDepts();
			for (LocalDept deptInfo : deptList){
				RTXDeptBean rtxDeptBean = (RTXDeptBean)deptInfo.getBindDepart();
				if (rtxDeptBean==null){
					rtxDeptBean = new RTXDeptBean(deptInfo);
					rtxDeptBean.setSubDepts(new ArrayList<RTXDeptBean>());
					rtxDeptBean.setParent(rtxParentBean);
					deptInfo.setBindDepart(rtxDeptBean);
					putDeptMap(rtxDeptBean, null, rootDept);
				}
				if (rtxDeptBean.getRelevanceId()==null) {
					// 添加为一个可删除节点
					try {
						orgService.loadRefObjectListMap(deptInfo);
					} catch (Exception e) {
						e.printStackTrace();
					}
					removeDepts.add(deptInfo);
		
					JSONObject jsonObject = new JSONObject();
		
					// 要删除节点
					jsonObject.put("id", "o-" + rtxDeptBean.getId());
					if (simpleData) {
						if (rtxParentBean != null) {
							jsonObjSetParent(jsonObject, rtxParentBean);
						}
					}
					jsonObject.put("isParent", true);
					jsonObject.put("open", (deptInfo.getLevel() < 3));
					if (deptInfo.getAllDepts().size() > 0 || deptInfo.getAllUsers().size() > 0) {
						jsonObject.put("name", deptInfo.getPath(parent) + deptInfo.getName() + "[删除]" + "("
								+ (deptInfo.getAllDepts().size() > 0 ? deptInfo.getAllDepts().size() + "部门" : "")
								+ (deptInfo.getAllUsers().size() > 0 ? deptInfo.getAllUsers().size() + "人" : "") + ")");
					} else {
						jsonObject.put("name", deptInfo.getPath(parent) + deptInfo.getName() + "[删除]") ;
					}
					jsonObject.put("delDeptId", rtxDeptBean.getId());

					JSONArray subNodes;
					if (!simpleData) {
						subNodes = new JSONArray();
					} else {
						subNodes = nodes;
					}
			
					// 递归处理下级部门
					if (depth == -1 || depth>1) {
						for(Object user: deptInfo.getUsers()){
							LocalUser userInfo = (LocalUser) user;
							if (userInfo.getBindUser()!=null){
								// 最新所属部门未被删除
							}
						}
						for (Object dept : deptInfo.getSubDepts()) {
							LocalDept subDept  = (LocalDept) dept;
							addRemoveSubDepts(subNodes, (RTXDeptBean)subDept.getBindDepart(), depth==-1?-1:depth-1, simpleData);
						}
						
					}
			
					if (!simpleData) {
						jsonObject.put("children", subNodes);
					}
					
					nodes.add(jsonObject);
					
				}
			}
		}
	}

	/**
	 * 添加该节下要删除的用户，部门节点忽略，集中到所属组织机构中处理
	 * 
	 * @param jsonArray
	 * @param rtxParentBean
	 * @param simpleData
	 */
	private void addRemoveUserList(JSONArray jsonArray, RTXDeptBean rtxParentBean, boolean simpleData) {
		List<LocalUser> userList;
	
		if (rtxParentBean.isOrganization()) {
			// 组织机构节点，处理所有要删除用户
			userList = rtxParentBean.getBindDept().getAllUsers();
		} else if (rtxParentBean.getOrg() == null) {
			// 组织机构以上级别节点，处理直属的要删除用户
			userList = rtxParentBean.getBindDept().getUsers();
		} else {
			// 部门及节点，要删除用户已经处理，不再重复处理
			userList = new ArrayList<LocalUser>();
		}
		for (LocalUser userInfo : userList) {
			RTXUserBean rtxUserBean = userInfo.getBindUser();
			// 筛选未匹配上的用户
			if(rtxUserBean==null){
				if (rootDept.getBindDept().getUserLoginNameMap().containsKey(userInfo.getUserName())){
					Set<Integer> userIds = (Set<Integer>) rootDept.getBindDept().getUserLoginNameMap().get(userInfo.getUserName());
					for(Integer userId:userIds){
						LocalUser localUser = (LocalUser) rootDept.getBindDept().getUserMap().get(userId) ;
						userInfo = localUser;
						rtxUserBean = userInfo.getBindUser();
					}
				}
			}
			if(rtxUserBean==null){
				rtxUserBean = new RTXUserBean();
				rtxUserBean.setName(userInfo.getName());
				rtxUserBean.setBindUser(userInfo);
				userInfo.setBindUser(rtxUserBean);
				putUserMap(rtxUserBean, null, rootDept);
			}
			if (rtxUserBean.getRelevanceId()==null) {
				JSONObject jsonObject = new JSONObject();

				// 要删除节点
				jsonObject.put("id", "ud-" + rtxUserBean.getId());
				if (simpleData) {
					if (rtxParentBean != null) {
						jsonObjSetParent(jsonObject, rtxParentBean);
					}
				}
				jsonObject.put("delUserId", rtxUserBean.getId());
				jsonObject.put("name", "[删除]" + userInfo.getName() + (userInfo.getName().equals(userInfo.getUserName())?"":"(" + userInfo.getUserName() + ")"));

				jsonArray.add(jsonObject);
			}
		}
		
	}
	
	public String getOrgTree(RTXDeptBean rtxDeptTreeNode) throws Exception {
		JSONArray jsonArray = new JSONArray();

		addUsersAndSubNodes(jsonArray, rtxDeptTreeNode, null, null, true, false, -1, simpleFormat);

		return jsonArray.toString();
	}

	/**
	 * 加载指定id的下级子节点
	 * @param id
	 * @param ids 业务对象
	 * @return
	 * @throws Exception
	 */
	public JSONArray getNodes(Integer id, Class<?> bizClass, Set<Integer> ids, boolean onlyAdd, int depth, LocalUser currentUser) throws Exception {
		JSONArray list = new JSONArray();

		RTXDeptBean rtxDept = getRtxDept(id, currentUser);
		
		if(rtxDept!=null){
			// 检查当前节点的下级节点是否解析过
			if (depth == -1 || depth >1){
				// 下级节点还未解析过
				loadSubDepts(rtxDept, ids==null, ids!=null&&LocalUser.class.isAssignableFrom(bizClass), depth==-1?-1:depth-1);
			}
			
			// 加载当前节点的子节点到
			RTXDeptBean syncRootDept = rtxDept.getSyncRootDept();
			addDeptNode(list, rtxDept, bizClass, ids, ids==null?syncRootDept!=null&&syncRootDept.getRelevanceId()!=null:null, onlyAdd, depth, simpleFormat);
		}
		
		return list;
	}

	/**
	 * 加载指定id的下级子节点
	 * @param parentId
	 * @param bizClass
	 * @param ids	已选择节点ids
	 * @param onlyAdd
	 * @param depth			遍历深度
	 * @param currentUser
	 * @return
	 * @throws Exception
	 */
	public JSONArray getSubNode(Integer parentId, Class<?> bizClass, Collection<Integer> ids, boolean onlyAdd, int depth, LocalUser currentUser) throws Exception {
		JSONArray list = new JSONArray();

		RTXDeptBean parentDeptBean = getRtxDept(parentId, currentUser);
		
		try {
			// 检查当前节点的下级节点是否解析过
			if (parentDeptBean.getSubDepts()==null){
				// 下级节点还未解析过
				loadSubDepts(parentDeptBean, ids==null, ids!=null&&LocalUser.class.isAssignableFrom(bizClass), depth);
			}
			
			// 加载当前节点的子节点到
			RTXDeptBean syncRootDept = parentDeptBean.getSyncRootDept();
			addUsersAndSubNodes(list, parentDeptBean, bizClass, ids, ids==null?syncRootDept!=null&&syncRootDept.getRelevanceId()!=null:null, onlyAdd, depth, simpleFormat);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return list;
	}

	/**
	 * 递归装配本地直属用户
	 * @param parentRtxDept
	 * @param localParentDept
	 * @param orgMap
	 * @throws Exception
	 */
	private void mountUsers(RTXDeptBean parentRtxDept) throws Exception{
		List<RTXUserBean> users = parentRtxDept.getUsers();
		if(users==null){
			users = new ArrayList<RTXUserBean>();
			parentRtxDept.setUsers(users);
		}else{
			users.clear();
		}
		Map<Integer, LocalUser> userMap = rootDept.getBindDept().getUserMap();
		if (userMap==null){
			userMap = new HashMap<Integer, LocalUser>();
			rootDept.getBindDept().setUserMap(userMap);
		}
		Map<String, Set<Integer>> userloginNameMap = rootDept.getBindDept().getUserLoginNameMap();
		if(userloginNameMap==null){
			userloginNameMap = new HashMap<String, Set<Integer>>();
			rootDept.getBindDept().setUserLoginNameMap(userloginNameMap);
		}
		LocalDept localParentDept = parentRtxDept.getBindDept();
		for(Object user:localParentDept.getUsers()){
			LocalUser localUser = (LocalUser) user;
			rootDept.getBindDept().dupUserCheck(localUser);
			
			RTXUserBean orgTreeUser = new RTXUserBean();
			orgTreeUser.setId(localUser.getPkId());
			orgTreeUser.setUserName(localUser.getUserName());
			orgTreeUser.setName(localUser.getName());
			orgTreeUser.setBindUser(localUser);
			localUser.setBindUser(orgTreeUser);

			orgTreeUser.addUserDept(parentRtxDept);
			parentRtxDept.getUsers().add(orgTreeUser);
		}
	}
	
	/**
	 * 递归装配本地直属用户及下级部门树，如果有远程关联的组织机构，根据配置检查远程关联关系
	 * @param parentRtxDept
	 * @param localParentDept
	 * @param orgMap
	 * @throws Exception
	 */
	private void mountSubDepts(RTXDeptBean parentRtxDept, int depth){
		if (depth==-1||depth>0){
			LocalDept localParentDept = parentRtxDept.getBindDept();
			if (parentRtxDept.getSubDepts()==null){
				parentRtxDept.setSubDepts(new ArrayList<RTXDeptBean>());
			}else{
				parentRtxDept.getSubDepts().clear();
			}
			for(Object dept:localParentDept.getSubDepts()){
				LocalDept localDept = (LocalDept) dept;
				mountDept(parentRtxDept, localDept, depth);
			}
		}
	}

	private RTXDeptBean mountDept(RTXDeptBean parentRtxDept, LocalDept localDept, int depth) {
		
		RTXDeptBean rtxDept = new RTXDeptBean(localDept);

		rtxDept.setParent(parentRtxDept);
		parentRtxDept.getSubDepts().add(rtxDept);
		rtxDept.setOrganization(DeptTypeEnum.ORG.equals(localDept.getDeptTypeEnum()));
		rtxDept.setRelevanceId(new Long(localDept.getIdType()));
		
		putDeptMap(rtxDept, null, rootDept);
		
		if (depth==-1||depth>1){
			mountSubDepts(rtxDept, depth==-1?-1:depth-1);
		}
		
		return rtxDept;
	}

	/**
	 * 解析下级节点
	 * @param rtxDept		当前节点
	 * @param syncCheck		是否需要进行同步检查
	 * @param loadUsers		是否需要加载用户
	 * @throws Exception
	 */
	public void loadSubDepts(RTXDeptBean rtxDept, boolean syncCheck, boolean loadUsers, int depth) throws Exception {
		LocalDept localDept = rtxDept.getBindDept();
		
		if(rtxDept.getSubDepts()==null){
			rtxDept.setSubDepts(new ArrayList<RTXDeptBean>());
		}else{
			rtxDept.getSubDepts().clear();
		}
		boolean rtxMountSuccess = false;
		
		// 是否需要检查远程组织机构同步，目前是没有其他业务操作时要检查
		if (syncCheck && localDept.isSyncNeed()){
			// 获取远程组织架构进行装配，腾讯通组织架构
			rtxMountSuccess = mountRelevanceDeptTreeWithUsers(rtxDept);
		}
		if (rtxMountSuccess){
			// 远程组织机构装配成功，
			// 加载所有下级组织机构
			orgService.loadSubDepts(localDept, "", -1);
			
			// 建立本组织机构缓存表
			Map<Integer, LocalDept> localDeptMap = rootDept.getBindDept().getDeptMap();
			if (localDeptMap==null){
				localDeptMap = new HashMap<Integer, LocalDept>();
				rootDept.getBindDept().setDeptMap(localDeptMap);
			}

			// 为了保证能完全，并且唯一地加载用，需要充根部门开始补充加载用户
			Map<Integer, LocalUser> localUserMap = rootDept.getBindDept().getUserMap();
			if (localUserMap==null){
				localUserMap = new HashMap<Integer, LocalUser>();
				rootDept.getBindDept().setUserMap(localUserMap);
			}

			for(Object dept: rtxDept.getBindDept().getAllDepts()){
				LocalDept localdept = (LocalDept) dept;
				putLocalDeptMap(localdept, rootDept.getBindDept());
			}
			
			for(LocalDept localDept2: localDeptMap.values()){
				orgService.loadUsers(localDept2);
				for(Object userObj: localDept2.getUsers()){
					LocalUser localUser = (LocalUser) userObj;
					if(localUserMap.containsKey(localUser.getPkId())){
						localUser = localUserMap.get(localUser.getPkId());
					}else{
						localUserMap.put(localUser.getPkId(), localUser);
						localUser.setUserDepts(new ArrayList<LocalDept>());
					}
					localUser.getUserDepts().add(localDept2);
				}
			}
			
			List<LocalUser> allLocalUser = rootDept.getBindDept().getAllUsers();
			
			rootDept.getBindDept().initLocalUserMap(allLocalUser);

			// 初始化同步部门下的用户关联表
			localDept.initUserRelevanceMap(allLocalUser);

			// 远程组织机构树 及 本地组织机构树均已装配完毕，绑定关系，并逐级进行匹配和绑定

			rtxDept.bind(localDept);
		}else{
			// 远程组织机构装配失败或者是无远程组织机构，依然按本地组织架构进行装配并自动绑定
			if (loadUsers){
				orgService.loadSubDepts(localDept, "users", 1);
				mountUsers(rtxDept);
			}else{
				orgService.loadSubDepts(localDept, "", 1);
			}
			mountSubDepts(rtxDept, 1);
			if(depth==-1||depth>1){
				for(Object dept:rtxDept.getSubDepts()){
					RTXDeptBean subDept = (RTXDeptBean) dept;
					loadSubDepts(subDept, syncCheck, loadUsers, depth==-1?-1:depth-1);
				}
			}
		}
	}

	private static void putDeptMap(RTXDeptBean rtxDept, RTXDeptBean syncRootDept, RTXDeptBean rootDept) {
		rootDept.putRtxDept(rtxDept);
		LocalDept localDept = rtxDept.getBindDept();
		LocalDept localRootDept = rootDept.getBindDept();
		putLocalDeptMap(localDept, localRootDept);
		if (syncRootDept!=null){
			syncRootDept.putRelevanceDept(rtxDept);
		}
	}

	private static void putLocalDeptMap(LocalDept localDept, LocalDept localRootDept) {
		if(localRootDept!=null) {
			Map<Integer, LocalDept> localDeptMap = localRootDept.getDeptMap();
			if(localDeptMap==null){
				localDeptMap = new HashMap<Integer, LocalDept>();
				localRootDept.setDeptMap(localDeptMap);
			}
			if(localDept!=null&&!localDeptMap.containsKey(localDept.getPkId())){
				localDeptMap.put(localDept.getPkId(), localDept);
			}
		}
	}

	private static void putUserMap(RTXUserBean rtxUser, RTXDeptBean syncRootDept, RTXDeptBean rootDept) {
		rootDept.getUserMap().put(rtxUser.getId(), rtxUser);
		if (syncRootDept!=null){
			syncRootDept.getRelevanceUserMap().put(rtxUser.getRelevanceId(), rtxUser);
		}
	}
	
	/**
	 * 获取组织机构树，包含用户，如果是远程组织架构，获取远程组织机构，并进行比对
	 * @throws Exception 
	 */
	public RTXDeptBean getRootDept(String funcKey, boolean rebuild, LocalUser currentUser){
		if (rebuild){
			rootDept = null;
		}
		if (rootDept==null){
			LocalDept localDeptRoot = orgService.getRootDept(rebuild, funcKey, currentUser);
			RTXDeptBean.cleanId();
			RTXUserBean.cleanId();
			rootDept = new RTXDeptBean(localDeptRoot);
			putDeptMap(rootDept, null, rootDept);
		}
		return rootDept;
	}
	
	public RTXDeptBean getRtxDept(Integer id, LocalUser currentUser) throws Exception{
		return getRootDept(null, false, currentUser).getRtxDept(id==null?0:id);
	}
	
	public RTXUserBean getRtxUser(Integer id, LocalUser currentUser) throws Exception{
		return (RTXUserBean) getRootDept(null, false, currentUser).getUserMap().get(id);
	}

	private boolean mountRelevanceDeptTreeWithUsers(RTXDeptBean rtxDept){
		boolean result = false;
		
		String relevanceType = rtxDept.getBindDept().getRelevanceType();
		LocalDept localDept = rtxDept.getBindDept();
		String relevanceConfig = localDept.getRelevanceConfig();
		Integer relevanceId = localDept.getIdType();
		String name = localDept.getName();
		if ("RTX".equals(relevanceType)){
			RTXClient rtxClient = RTXClient.getInstance(relevanceConfig);
			RTXDept rDept;
			try {
				rDept = rtxClient.getRelevanceDeptTree(relevanceId, name);
			} catch (Exception e) {
				e.printStackTrace();
				rDept = null;
			}
			if (rDept!=null){
				rtxDept.setRelevanceId(rDept.getDeptId()==null?0:rDept.getDeptId().longValue());
				rtxDept.setRelevanceDeptMap(new HashMap<Long, RTXDeptBean>());
				rtxDept.setRelevanceUserMap(new HashMap<Long, RTXUserBean>());
				rtxDept.putRelevanceDept(rtxDept);
				mountSubDeptTree(rtxDept, rDept, rtxDept, rootDept);
				result = true;
			}
		}else if("DingTalk".equals(relevanceType)){
			DingTalkClient dingTalkClient = DingTalkClient.getInstance(relevanceConfig);
			Department department;
			try {
				department = dingTalkClient.getDeptTree();
			} catch (Exception e) {
				e.printStackTrace();
				department = null;
			}
			if (department!=null){
				rtxDept.setRelevanceId(department.getId()==null?0:department.getId().longValue());
				rtxDept.setRelevanceDeptMap(new HashMap<Long, RTXDeptBean>());
				rtxDept.setRelevanceUserMap(new HashMap<Long, RTXUserBean>());
				mountSubDeptTree(rtxDept, department, rtxDept, rootDept);
				result = true;
			}
		}

		
		return result;
	}

	/**
	 * 递归装配子部门树
	 * @param rtxDept
	 * @param rDept
	 */
	private void mountSubDeptTree(RTXDeptBean rtxDept, RTXDept rDept, RTXDeptBean syncRootDept, RTXDeptBean rootDept) {
		if (rDept!=null&&rDept!=null){
			if (rtxDept.getSubDepts()==null){
				rtxDept.setSubDepts(new ArrayList<RTXDeptBean>());
			}else{
				rtxDept.getSubDepts().clear();
			}
			log.info("递归装配子部门树");
			if (rDept.getSubDepts()!=null){
				for(Object dept:rDept.getSubDepts()){
					RTXDept subDept = (RTXDept) dept;
					RTXDeptBean rtxSubDept = new RTXDeptBean();
					
					rtxSubDept.setParent(rtxDept);
					
					if(rtxDept.getId()!=null){
						rtxSubDept.setParentId(rtxDept.getId());
					}
					rtxSubDept.setRelevanceId(subDept.getDeptId().longValue());
					rtxSubDept.setDeptName(subDept.getDeptName());
					
					putDeptMap(rtxSubDept, syncRootDept, rootDept);
					
					rtxDept.getSubDepts().add(rtxSubDept);
					mountSubDeptTree(rtxSubDept, subDept, syncRootDept,rootDept);
				}
			}
			if(rtxDept.getUsers()==null){
				rtxDept.setUsers(new ArrayList<RTXUserBean>());
			}else{
				rtxDept.getUsers().clear();
			}
			if(rDept.getUsers()!=null){
				for(Object ru:rDept.getUsers()){
					RTXUser user = (RTXUser) ru;
					String rtxUserId = "" + user.getId();
					RTXUserBean rtxUser;
					if (syncRootDept.getRelevanceUserMap().containsKey(rtxUserId)){
						rtxUser = (RTXUserBean) syncRootDept.getRelevanceUserMap().get(rtxUserId);
					}else{
						rtxUser = new RTXUserBean();
						
						rtxUser.setRelevanceId(rtxUserId);
						rtxUser.setUserName(user.getUserName());
						rtxUser.setName(user.getName());
						
						putUserMap(rtxUser, syncRootDept, rootDept);
					}
					rtxUser.addUserDept(rtxDept);
					
					rtxDept.getUsers().add(rtxUser);
				}
			}
		}
	}

	/**
	 * 递归装配子部门树
	 * @param rtxDept
	 * @param depart
	 */
	private void mountSubDeptTree(RTXDeptBean rtxDept, Department depart, RTXDeptBean syncRootDept, RTXDeptBean rootDept) {
		if (rtxDept!=null&&depart!=null){
			if (rtxDept.getSubDepts()==null){
				rtxDept.setSubDepts(new ArrayList<RTXDeptBean>());
			}else{
				rtxDept.getSubDepts().clear();
			}
			log.info("递归装配子部门树");
			if (depart.getSubDepartments()!=null){
				for(Department subDept:depart.getSubDepartments()){
					RTXDeptBean rtxSubDept = new RTXDeptBean();
					
					rtxSubDept.setParent(rtxDept);
					
					if(rtxDept.getRelevanceId()!=null){
						rtxSubDept.setParentId(rtxDept.getId());
					}
					rtxSubDept.setRelevanceId(subDept.getId());
					rtxSubDept.setDeptName(subDept.getName());
					
					putDeptMap(rtxSubDept, syncRootDept, rootDept);
					
					rtxDept.getSubDepts().add(rtxSubDept);
					
					mountSubDeptTree(rtxSubDept, subDept, syncRootDept, rootDept);
				}
			}
			
			if(rtxDept.getUsers()==null){
				rtxDept.setUsers(new ArrayList<RTXUserBean>());
			}else{
				rtxDept.getUsers().clear();
			}
			if(depart.getMember()!=null){
				if (rtxDept.getUsers()==null){
					rtxDept.setUsers(new ArrayList<RTXUserBean>());
				}else{
					rtxDept.getUsers().clear();
				}
				for(User user:depart.getMember()){
					RTXUserBean rtxUser;
					if (syncRootDept.getRelevanceUserMap().containsKey(user.getDingId())){
						rtxUser = (RTXUserBean) syncRootDept.getRelevanceUserMap().get(user.getDingId());
					}else{
						rtxUser = new RTXUserBean();

						rtxUser.setRelevanceId(user.getDingId());
						rtxUser.setUserName(user.getName());
						rtxUser.setName(user.getName());
						rtxUser.setMobile(user.getMobile());
						rtxUser.setEmail(user.getEmail());
						rtxUser.setPosition(user.getPosition());
						
						putUserMap(rtxUser, syncRootDept, rootDept);
					}
					rtxUser.addUserDept(rtxDept);
					
					rtxDept.getUsers().add(rtxUser);
				}
			}
		}
	}

	public int updateDepts(List<Integer> updDeptIds, LocalUser currentUser) throws Exception {
		int count = 0;
		
		for(Integer id:updDeptIds){
			RTXDeptBean deptBean = getRtxDept(id, currentUser);
			if (deptBean!=null){
				LocalDept deptInfo = deptBean.getBindDept();
				if (deptBean.getRelevanceId()!=null){
					deptInfo.setName(deptBean.getDeptName());
					deptInfo.setParId(deptBean.getParent().getBindDept().getPkId());
					deptInfo.setIdType(deptBean.getRelevanceId().intValue());
					try {
						orgService.update(deptInfo);
						count++;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		return count;
	}

	public int addDepts(List<Integer> addDeptIds, LocalUser currentUser) throws Exception {
		int count = 0;
		LocalDept localRootDept = null;
		
		for(Integer id:addDeptIds){
			RTXDeptBean deptBean = getRtxDept(id, currentUser);
			if (deptBean!=null){
				LocalDept deptInfo = deptBean.getBindDept();
				if (deptInfo==null&&deptBean.getRelevanceId()!=null){
					deptInfo = orgService.getNew();
					deptInfo.setName(deptBean.getDeptName());
					deptInfo.setParent(deptBean.getParent().getBindDept());
					deptInfo.setIdType(deptBean.getRelevanceId().intValue());
					deptInfo.setLevel(deptInfo.getRealLevel());
					try {
						LocalDept deptInfoPo = orgService.save(deptInfo);
						deptBean.bind(deptInfoPo);
						deptInfoPo.setParent(deptBean.getParent().getBindDept());
						if (localRootDept==null){
							localRootDept = rootDept.getBindDept();
						}
						putLocalDeptMap(deptInfo, localRootDept);
						
						count++;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		return count;
	}

	/**
	 * 
	 * @param updUserIds
	 * @return
	 * @throws Exception
	 */
	public int updateUsers(List<Integer> updUserIds, LocalUser currentUser) throws Exception {
		int count = 0;
		
		for(Integer id:updUserIds){
			RTXUserBean userBean = getRtxUser(id, currentUser);
			if (userBean!=null){
				LocalUser userInfo = userBean.getBindUser();
				
				// 检查并合并重名用户
				if(userInfo!=null){
					List<LocalDept> userDepts = userInfo.getUserDepts();
					Set<Integer> userIds;
					try {
						userIds = (Set<Integer>) rootDept.getBindDept().getUserLoginNameMap().get(userInfo.getUserName());
					} catch (Exception e) {
						e.printStackTrace();
						userIds = null;
					}
					if(userIds!=null&&userIds.size()>1){
						List<LocalUser> list = new ArrayList<LocalUser>();
						for(Integer userId:userIds){
							LocalUser localUser = (LocalUser) rootDept.getBindDept().getUserMap().get(userId);
							list.add(localUser);
						}
						
						userInfo = userService.merge((List<LocalUser>) list, null);
						userInfo.setUserDepts(userDepts);
						userBean.setBindUser(userInfo);
					}
				}
				if (userInfo!=null&&userBean.getRelevanceId()!=null){
					userInfo.setUserName(userBean.getUserName());
					userInfo.setName(userBean.getName());
					userInfo.setIdType(userBean.getRelevanceId());
					userInfo.setTelPhone(userBean.getMobile());
					userInfo.setEmail(userBean.getEmail());
					Set<LocalDept> removeSet = new HashSet<LocalDept>();
					for(Object d:userInfo.getUserDepts()){
						LocalDept dept = (LocalDept) d;
						try {
							LocalDept userDept = (LocalDept) rootDept.getBindDept().getDeptMap().get(dept.getPkId());
							if(!userBean.affiliatedWithDepart((RTXDeptBean) userDept.getBindDepart())){
								removeSet.add(dept);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					for(LocalDept userDept:removeSet){
						userInfo.removeUserDept(userDept);
					}
					for(RTXDeptBean rtxUserDept:userBean.getUserDepts()){
						if (rtxUserDept.getBindDept()!=null){
							LocalDept localUserDept;
							try {
								localUserDept = (LocalDept) rootDept.getBindDept().getDeptMap().get(rtxUserDept.getBindDept().getPkId());
							} catch (Exception e) {
								localUserDept = null;
								e.printStackTrace();
							}
							userInfo.addUserDept(localUserDept);
						}
					}
					try {
						userService.update(userInfo, "userName,name,idType,userDepts");
						count++;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		return count;
	}

	public int addUsers(List<Integer> addUserIds, LocalUser currentUser) throws Exception {
		int count = 0;
		
		// 组织机构默认角色列表缓存
		Map<Integer, List<LocalRole>> orgRoleListCache = new HashMap<Integer, List<LocalRole>>();
		
		for(Integer id:addUserIds){
			RTXUserBean userBean = getRtxUser(id, currentUser);
			if (userBean!=null){
				LocalUser userInfo = userBean.getBindUser();
				if (userInfo==null&&userBean.getRelevanceId()!=null){
					userInfo = userService.getNew();
					userInfo.setUserName(userBean.getUserName());
					userInfo.setName(userBean.getName());
					userInfo.resetPassword();
					userInfo.setTelPhone(userBean.getMobile());
					userInfo.setEmail(userBean.getEmail());
					Map<Integer, LocalRole> roleMap = new HashMap<Integer, LocalRole>();
					for(RTXDeptBean rtxUserDept:userBean.getUserDepts()){
						LocalDept localUserDept = rtxUserDept.getBindDept();
						userInfo.addUserDept(localUserDept);
						List<LocalRole> defaultRoleList = orgRoleListCache.get(localUserDept.getOrgId());
						if(defaultRoleList==null) {
							defaultRoleList = roleInfoService.getDefaultRolesByOrgId(localUserDept.getOrgId());
							orgRoleListCache.put(localUserDept.getOrgId(), defaultRoleList);
						}
						for(LocalRole localRole:defaultRoleList) {
							if(!roleMap.containsKey(localRole.getPkId())) {
								roleMap.put(localRole.getPkId(), localRole);
							}
						}
					}
					userInfo.setIdType(userBean.getRelevanceId());
					userInfo.setRoles(new ArrayList<LocalRole>(roleMap.values()));
					try {
						userInfo = userService.save(userInfo);
						userBean.setBindUser(userInfo);
						userInfo.setBindUser(userBean);
						count++;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		return count;
	}

	public Map<String, Object> delUsers(List<Integer> delUserIds, LocalUser currentUser) {
		Map<String, Object> result = new HashMap<String, Object>();
		int count = 0;
		int errorCount = 0;
		String errorMessage = "";
		
		for(Integer id:delUserIds){
			RTXUserBean userBean;
			try {
				userBean = getRtxUser(id, currentUser);
			} catch (Exception e1) {
				userBean = null;
			}
			if (userBean!=null){
				LocalUser userInfo = userBean.getBindUser();
				if (userInfo!=null){
					try {
						if(userService.delete(userInfo)){
							userBean.setBindUser(null);
							count++;
						}
					} catch (Exception e) {
						if (errorCount==0){
							errorMessage += ""+e.getMessage();
						}
						errorCount++;
					}
				}
			}
		}
		
		result.put("count", count);
		result.put("errorCount", errorCount);
		result.put("errorMessage", errorMessage);
		return result;
	}

	public int delDepts(List<Integer> delDeptIds, LocalUser currentUser) throws Exception {
		int count = 0;
		
		for(Integer id:delDeptIds){
			RTXDeptBean deptBean = getRtxDept(id, currentUser);
			if (deptBean!=null){
				LocalDept deptInfo = deptBean.getBindDept();
				if (deptInfo!=null){
					try {
						orgService.delete(deptInfo);
						count++;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		
		return count;
	}

	public String getOrgManageRight() {
		return orgService.getOrgManageRight();
	}

}
